<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useUserStore } from '../stores/user'
import { useChatStore } from '../stores/chat'
import { useContentStore } from '../stores/content'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const chatStore = useChatStore()
const contentStore = useContentStore()

const currentLanguage = computed(() => contentStore.currentLanguage)
const message = ref('')
const chatContainerRef = ref(null)
const loading = ref(false)
const historyLoaded = ref(false)  // 标记是否已加载历史记录

// 当前聊天记录
const currentChat = computed(() => chatStore.currentChat)

// 发送消息
async function sendMessage() {
  if (!message.value.trim()) {
    return
  }
  
  const userMessage = message.value
  message.value = ''
  loading.value = true
  
  try {
    await chatStore.sendMessage(userMessage)
    await nextTick()
    scrollToBottom()
  } catch (error) {
    ElMessage.error(currentLanguage.value === 'zh' ? '发送消息失败' : 'Failed to send message')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 加载聊天历史
async function loadChatHistory() {
  if (userStore.isLoggedIn && !historyLoaded.value) {
    loading.value = true
    try {
      await chatStore.fetchChatHistory()
      
      // 如果有历史记录，将其添加到当前聊天
      if (chatStore.chatHistory.length > 0) {
        chatStore.initCurrentChatFromHistory()
        await nextTick()
        scrollToBottom()
      }
      historyLoaded.value = true
    } catch (error) {
      console.error('加载聊天历史失败:', error)
    } finally {
      loading.value = false
    }
  }
}

// 清除聊天记录
function clearChat() {
  chatStore.clearCurrentChat()
}

// 滚动到底部
function scrollToBottom() {
  if (chatContainerRef.value) {
    chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight
  }
}

onMounted(async () => {
  // 如果用户已登录，加载聊天历史
  if (userStore.isLoggedIn) {
    await loadChatHistory()
  } else {
    // 如果不是登录状态，自动发送一条欢迎消息
    chatStore.currentChat.push({
      user_message: '',
      ai_response: currentLanguage.value === 'zh' 
        ? '你好！我是Laya，来华留学智能助手。有什么可以帮你的吗？'
        : 'Hello! I am Laya, your Study in China AI assistant. How can I help you?',
      created_at: new Date().toISOString()
    })
  }
  
  // 确保聊天区域滚动到底部
  await nextTick()
  scrollToBottom()
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>{{ currentLanguage === 'zh' ? 'AI智能助手' : 'AI Assistant' }}</h2>
      <div class="chat-actions">
        <el-button v-if="userStore.isLoggedIn" type="text" @click="loadChatHistory">
          {{ currentLanguage === 'zh' ? '刷新历史' : 'Refresh History' }}
        </el-button>
        <el-button type="text" @click="clearChat">
          {{ currentLanguage === 'zh' ? '清除聊天' : 'Clear Chat' }}
        </el-button>
      </div>
    </div>
    
    <div class="chat-messages" ref="chatContainerRef">
      <div v-if="loading && currentChat.length === 0" class="loading-container">
        <el-loading></el-loading>
      </div>
      
      <div v-else-if="currentChat.length === 0" class="empty-chat">
        <el-empty :description="currentLanguage === 'zh' ? '开始聊天吧' : 'Start chatting'" />
      </div>
      
      <div v-else>
        <div 
          v-for="(chat, index) in currentChat" 
          :key="index"
          class="message-container"
        >
          <!-- 用户消息 -->
          <div v-if="chat.user_message" class="message user-message">
            <div class="message-content">
              {{ chat.user_message }}
            </div>
            <div class="message-time">{{ new Date(chat.created_at).toLocaleTimeString() }}</div>
          </div>
          
          <!-- AI回复 -->
          <div class="message ai-message">
            <div class="message-content">
              {{ chat.ai_response }}
            </div>
            <div class="message-time">{{ new Date(chat.created_at).toLocaleTimeString() }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <el-input
        v-model="message"
        :placeholder="currentLanguage === 'zh' ? '输入消息...' : 'Type a message...'"
        :disabled="loading"
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button :loading="loading" @click="sendMessage">
            {{ currentLanguage === 'zh' ? '发送' : 'Send' }}
          </el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200px);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  color: #409EFF;
}

.chat-actions {
  display: flex;
  gap: 10px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.loading-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-chat {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-container {
  margin-bottom: 20px;
}

.message {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 10px;
  margin-bottom: 5px;
  position: relative;
}

.user-message {
  margin-left: auto;
  background-color: #409EFF;
  color: white;
  border-top-right-radius: 0;
}

.ai-message {
  margin-right: auto;
  background-color: #F2F6FC;
  color: #303133;
  border-top-left-radius: 0;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
  margin-top: 5px;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input {
  padding: 15px 20px;
  border-top: 1px solid #EBEEF5;
}
</style> 